<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="920px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      :inline="true"
      v-loading="formLoading"
    >
      <el-row>
        <el-col>
          <el-alert
            title="注：请让您的车队长关注承运商小程序，以便能使用承运商小程序！联系电话即为登录账号，默认密码tslbdp@123456。"
            type="warning"
            show-icon
            :closable="false"
            style="margin-bottom: 15px"
          />
          <el-form-item label="车队长类型" prop="carrierType">
            <el-radio-group v-model="formData.carrierType" :disabled="formType != 'create'">
              <el-radio
                v-for="dict in getIntDictOptions(DICT_TYPE.CAPTAIN_TYPE)"
                :key="dict.value"
                :label="dict.value"
              >
                {{dict.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="所属承运商" prop="parentCarrierUscc">
            <el-select
              v-model="formData.parentCarrierUscc"
              placeholder="请输入所属承运商"
              style="width: 240px"
            >
              <el-option
                v-for="item in carrierList"
                :key="item.carrierUscc"
                :label="item.carrierName"
                :value="item.carrierUscc"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车队长名称" prop="carrierName">
            <el-input v-model="formData.carrierName" placeholder="请输入承运商/车队长名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="信用代码/身份证" prop="carrierUscc">
            <el-input v-model="formData.carrierUscc" placeholder="请输入统一社会信用代码/身份证" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="法人代表" prop="legalPerson" v-if="formData.carrierType != 0">
            <el-input v-model="formData.legalPerson" placeholder="请输入法人代表" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="法人身份证" prop="legalIdCardNo" v-if="formData.carrierType != 0">
            <el-input v-model="formData.legalIdCardNo" placeholder="请输入法人身份证" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号" prop="carrierPhone">
            <el-input v-model="formData.carrierPhone" placeholder="请输入承运商手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款方式" prop="paymentMethod">
            <el-select
              v-model="formData.paymentMethod"
              placeholder="请选择付款方式"
              style="width: 200px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PAYMENT_METHOD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="营业执照" prop="blUrl" v-if="formData.carrierType != 0">
        <el-upload
          ref="uploadRef"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="handleChange"
          v-model:file-list="formData.blFiles"
          :class="{ disabled: uploadDisabled }"
          :limit="1"
        >
          <el-icon><UploadFilled /></el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
              <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
            </div>
          </template>
        </el-upload>
        <el-image-viewer
          v-if="fileVisible"
          @close="closeViewer"
          :url-list="[dialogImageUrl]"
        />
      </el-form-item>
    </el-form>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>银行账户信息</span>
          <div style="float: right">
            <el-button v-if="formType != 'show'" type="primary" @click="insertEvent(0)"
            >新增
            </el-button>
            <el-button type="danger" @click="removeSelectRowEvent(0)">删除</el-button>
          </div>
        </div>
      </template>
      <el-row>
        <el-col>
          <vxe-table
            border
            show-overflow
            keep-source
            ref="xTable"
            :column-config="{ resizable: true }"
            :loading="loading"
            max-height="400"
            :data="tableData"
            :edit-rules="validRules"
            :edit-config="{ trigger: 'manual', mode: 'row', autoClear: false, showStatus: true }"
          >
            <vxe-column type="checkbox" width="60" />
            <vxe-column title="序号" type="seq" width="60" />
            <vxe-column
              field="goodsName"
              title="货物名称"
              :edit-render="{ autofocus: '.vxe-input--inner', defaultValue: '' }"
            >
              <template #edit="{ row }">
                <vxe-input v-model="row.goodsName" type="text" />
              </template>
            </vxe-column>
            <vxe-column field="goodsType" title="货物类型" :edit-render="{ defaultValue: '' }">
              <template #default="{ row }">
                <dict-tag :type="DICT_TYPE.CATEGORY_TYPE" :value="row.goodsType" />
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.goodsType" transfer>
                  <vxe-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.CATEGORY_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="packType" title="包装类型" :edit-render="{ defaultValue: '' }">
              <template #default="{ row }">
                <dict-tag :type="DICT_TYPE.PACK_TYPE" :value="row.packType" />
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.packType" transfer>
                  <vxe-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.PACK_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="num" title="数量" :edit-render="{ defaultValue: '' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.num" type="text" />
              </template>
            </vxe-column>
            <vxe-column field="unit" title="单位" :edit-render="{ defaultValue: '' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.unit" type="text" />
              </template>
            </vxe-column>
            <vxe-column title="操作" width="160">
              <template #default="{ row }">
                <template v-if="isActiveStatus(row)">
                  <vxe-button @click="saveRowEvent(row)">保存</vxe-button>
                  <vxe-button @click="cancelRowEvent(row)">取消</vxe-button>
                </template>
                <template v-else>
                  <vxe-button @click="editRowEvent(row)">编辑</vxe-button>
                </template>
              </template>
            </vxe-column>
          </vxe-table>
        </el-col>
      </el-row>
    </el-card>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CarrierApi, CarrierVO } from '@/api/base/carrier'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from "@/utils/dict";
import type { UploadFile } from 'element-plus'
import { Delete, ZoomIn, UploadFilled } from '@element-plus/icons-vue'
/** 承运商管理 表单 */
defineOptions({ name: 'CarrierForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const uploadDisabled = ref(false)
const disabled = ref(false)
const dialogImageUrl = ref('')
const carrierList = ref([])
const dialogVisible = ref(false) // 弹窗的是否展示
const fileVisible = ref(false)
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  carrierName: undefined,
  carrierType: 0,
  carrierUscc: undefined,
  carrierPhone: undefined,
  legalPerson: undefined,
  legalIdCardNo: undefined,
  blUrl: undefined,
  paymentMethod: undefined,
  deptId: undefined,
  blFiles: []
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  carrierList.value = await CarrierApi.getCarrierList({
    neParentCarrierUscc: '0'
  })
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CarrierApi.getCarrier(id)
      if (formData.value.blUrl && formData.value.blUrl != '' ) {
        uploadDisabled.value = true
        formData.value.blFiles = [
          {
            url: formData.value.blUrl
          }
        ]
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    // const data = formData.value as unknown as CarrierVO
    var paramsData = new FormData()
    if(formData.value.id != undefined){
      paramsData.append('id', formData.value.id)
    }
    if(formData.value.parentCarrierUscc != undefined){
      paramsData.append('parentCarrierUscc', formData.value.parentCarrierUscc)
      const carrierData = carrierList.value.find((item) => {
        return item.carrierUscc == formData.value.parentCarrierUscc
      })
      paramsData.append('parentCarrierName', carrierData.carrierName)
    }
    if(formData.value.carrierName != undefined){
      paramsData.append('carrierName', formData.value.carrierName)
    }
    if(formData.value.carrierType != undefined){
      paramsData.append('carrierType', formData.value.carrierType)
    }
    if(formData.value.carrierUscc != undefined){
      paramsData.append('carrierUscc', formData.value.carrierUscc)
    }
    if(formData.value.carrierPhone != undefined){
      paramsData.append('carrierPhone', formData.value.carrierPhone)
    }
    if(formData.value.legalPerson != undefined){
      paramsData.append('legalPerson', formData.value.legalPerson)
    }
    if(formData.value.legalIdCardNo != undefined){
      paramsData.append('legalIdCardNo', formData.value.legalIdCardNo)
    }
    if(formData.value.paymentMethod != undefined){
      paramsData.append('paymentMethod', formData.value.paymentMethod)
    }
    console.log(formData.value.blFiles)
    console.log(formData.value.blFiles.length)
    console.log(formData.value.blFiles.length != 0)
    console.log(formData.value.blFiles.length != 0 && typeof formData.value.blFiles[0].raw != 'undefined')
    if (formData.value.blFiles.length != 0 && typeof formData.value.blFiles[0].raw != 'undefined') {
      paramsData.append('file', formData.value.blFiles[0].raw)
    }
    if (formType.value === 'create') {
      await CarrierApi.createCarrier(paramsData)
      message.success(t('common.createSuccess'))
    } else {
      await CarrierApi.updateCarrier(paramsData)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    carrierName: undefined,
    carrierType: 0,
    carrierUscc: undefined,
    carrierPhone: undefined,
    legalPerson: undefined,
    legalIdCardNo: undefined,
    blUrl: undefined,
    paymentMethod: undefined,
    deptId: undefined,
    blFiles: []
  }
  formRef.value?.resetFields()
}

const handleChange = (file: any, fileList: any) => {
  formData.value.blFiles = fileList
  uploadDisabled.value = fileList.length >= 1
}

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url
  fileVisible.value = true
}

const handleRemove = () => {
  uploadDisabled.value = false
  formData.value.blFiles = []
}

const closeViewer = () => {
  fileVisible.value = false
}
</script>
<style rel="stylesheet/scss" lang="scss">
.disabled .el-upload--picture-card {
  display: none;
}
</style>
